package spring.aop.cglibproxy;

import java.lang.reflect.Method;

import org.springframework.cglib.core.ReflectUtils;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Factory;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

public class MyCGLibProxy extends A implements Factory {
    private static MethodProxy methodProxy;
    private MethodInterceptor methodInterceptor;
    private static Method method;
    public MyCGLibProxy(MethodInterceptor methodInterceptor) {
        this.methodInterceptor = methodInterceptor;
    }
    static {
        try {
            final Class<?> forName = Class
                    .forName("spring.aop.cglibproxy.MyCGLibProxy");
            final Class<?> forName3 = Class.forName("spring.aop.cglibproxy.A");
            // 构建方法代理对象
            methodProxy = MethodProxy.create((Class<?>) forName3,
                    (Class<?>) forName,
                    "(Ljava/lang/String;)Ljava/lang/String;", "say",
                    "sayProxy");
            method = ReflectUtils.findMethods(
                    new String[]{"say",
                    "(Ljava/lang/String;)Ljava/lang/String;"},
                    forName3.getDeclaredMethods())[0];
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * cglib重写的子类的方法
     */
    @Override
    public void say(String s) {
        try {
            methodInterceptor.intercept((Object)this, method, new Object[] {s}, methodProxy);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    /**
     * @author GY
     * @date 2019年1月27日
     * @说明: 这个方法就是原样调用父类方法，即看作就是父类中被代理的方法本身
     */
    public void sayProxy(String s) {
        super.say(s);
    }

    @Override
    public Callback getCallback(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public Callback[] getCallbacks() {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public Object newInstance(Callback arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public Object newInstance(Callback[] arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public Object newInstance(Class[] arg0, Object[] arg1, Callback[] arg2) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void setCallback(int arg0, Callback arg1) {
        // TODO Auto-generated method stub
        
    }
    @Override
    public void setCallbacks(Callback[] arg0) {
        // TODO Auto-generated method stub
        
    }
}
